import { createReactBlockSpec } from "@blocknote/react";
import { useEffect, useRef, useState } from "react";
import { Button, Col, Divider, Flex, Row } from "antd";
import { RiImage2Fill, RiEdit2Fill } from "react-icons/ri";
import ReactCodeMirror from "@uiw/react-codemirror";
import { langs } from "@uiw/codemirror-extensions-langs";
import { useDebounce } from "ahooks";
import mermaid from "mermaid";

function Mermaid(props: {
  chart: string,
  theme?: string,
}) {
  const panelRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    panelRef.current?.removeAttribute('data-processed')
    panelRef.current?.replaceChildren(props.chart)

    mermaid.initialize({
      startOnLoad: true,
      theme: props.theme == null ? 'default' : props.theme,
      themeVariables: {
        handdrawn: true,
      },
    })
    mermaid.contentLoaded()
  }, [props.chart, props.theme])

  return <div className="mermaid" ref={panelRef}>
    {props.chart}
  </div>
}

export const MermaidBlock = createReactBlockSpec({
  type: 'mermaid',
  propSchema: {
    chart: {
      default: '',
    },
    theme: {
      default: 'default',
      values: ['default', 'neutral', 'dark', 'forest', 'base'],
    },
    showEditor: {
      default: true,
    },
  },
  content: 'none',
}, {
  render: ({ block, editor }) => {
    const [chart, setChart] = useState(block.props.chart)
    const [theme, setTheme] = useState(block.props.theme)
    const [showEditor, setShowEditor] = useState(block.props.showEditor)
    const chartDebounce = useDebounce(chart, { wait: 500 })

    const onChangeChart = (chart: string) => {
      setChart(chart)
      editor.updateBlock(block, {
        props: {
          chart: chart
        }
      })
    }

    const onClickShowEditor = () => {
      const show = !showEditor
      setShowEditor(show)
      editor.updateBlock(block, {
        props: {
          showEditor: show,
        }
      })
    }

    // 弃用
    const onThemeChange = (selectedTheme: "default" | "neutral" | "dark" | "forest" | "base") => {
      setTheme(selectedTheme)
      editor.updateBlock(block, {
        props: {
          theme: selectedTheme,
        }
      })
    }

    return <div style={{ display: 'block', height: '100%', width: '100%', border: '1px solid #ccc' }}>
      <Row>
        <Col span={24} style={{ padding: 3 }}>
          <Button onClick={onClickShowEditor}>
            {showEditor ? <RiImage2Fill /> : <RiEdit2Fill />}
          </Button>
        </Col>
      </Row>
      <Divider style={{ margin: 3 }} />
      <Flex style={{}}>
        <div style={{
          width: '50%',
          borderRight: '1px solid #EEE',
          display: showEditor ? 'block' : 'none',
        }}>
          <ReactCodeMirror
            value={chart}
            // autoFocus={editor.isEditable} // FIXME: 选中有问题,blockNote交互的问题
            onChange={(data: string) => { onChangeChart(data) }}
            extensions={[langs['mermaid']()]}
          ></ReactCodeMirror>
        </div>
        <div style={{
          width: showEditor ? '49%' : '99%'
        }}>
          <Mermaid chart={chartDebounce} theme={theme} />
        </div>
      </Flex >
    </div >
  }
})
